package com.robot.member.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.robot.member.client.MerchantClient;
import com.robot.member.client.OrdersClient;
import com.robot.member.pojo.Complaint;
import com.robot.member.pojo.client.Store;
import com.robot.member.service.ComplaintService;
import com.robot.member.service.MemberService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * complaint控制器层
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/complaint")
public class ComplaintController {
    @Autowired
    private ComplaintService complaintService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private MerchantClient merchantClient;
    @Autowired
    private OrdersClient ordersClient;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 店铺Store表status=0-禁用 1-启用
     */
    private final String storeStatusEnable = "1";


    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.SUCCESS_QUERY, complaintService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "admin/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(StatusCode.SUCCESS_QUERY, complaintService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Complaint> pageList = complaintService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<Complaint>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, complaintService.findSearch(searchMap));
    }

    /**
     * 增加投诉
     *
     * @param complaint
     */
//    @PostMapping("{storeId}")
//    public Result add(@PathVariable String storeId, @RequestBody Complaint complaint) {
//        Claims claims = (Claims) request.getAttribute("robot_member");
//        if (claims == null) {
//            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
//        }
//        logger.info("claims.getId()=" + claims.getId());
//        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断
//
//        if (complaint.getContent() == null || "".equals(complaint.getContent())) {
//            return new Result(StatusCode.ERROR_CONTENT_REQUIRED);
//        }
//
//        complaint.setMemberId(claims.getId());
//        Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(storeId), Store.class);
//        if (storeInDb == null || !storeStatusEnable.equals(storeInDb.getStatus())) {
//            return new Result(StatusCode.ERROR_STORE_DOES_NOTE_EXIST, "该店铺不存在或者异常,暂无法使用");
//        }
//
//        //只有下单成功的用户才可以投诉
//        JSONObject ordersInDb = JSON.parseObject(ordersClient.thirdFindSubOrdersByMemberIdAndStoreIdAndStatus(claims.getId(), storeInDb.getId(), "1", 1, 3));
//        String total = "total";
//        if ((Integer) ordersInDb.get(total) == 0) {
//            return new Result(StatusCode.ERROR_MEMBER_NO_ORDERS_INVALID);
//        }
//        complaint.setStoreId(storeInDb.getId());
//        complaint.setStoreName(storeInDb.getStoreName());
//        complaint.setCompanyId(storeInDb.getCompanyId());
//        complaintService.add(complaint);
//        return new Result(StatusCode.SUCCESS, "发表投诉成功");
//    }

    /**
     * 修改
     *
     * @param complaint
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody Complaint complaint, @PathVariable String id) {
        complaint.setId(id);
        complaintService.update(complaint);
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "deleteById/{id}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Complaint complaintInDb = complaintService.findByIdAndMemberId(id, claims.getId());
        logger.info("complaintInDb=" + complaintInDb);
        if (complaintInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        complaintInDb.setDeletedAt(LocalDateTime.now());
        complaintService.update(complaintInDb);
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 根据memberID查找会员名下所有投诉并分页
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("{page}/{size}")
    public Result findComplaintsByMemberId(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Page<Complaint> pageData = complaintService.findAllByMemberIdAndDeletedAtIsNullOrderByCreatedAtDesc(claims.getId(), page, size);
        logger.info("pageData=" + pageData);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 根据memberID和status查找会员名下所有投诉并分页
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("{status}/{page}/{size}")
    public Result findComplaintsByMemberIdAndStatus(@PathVariable String status, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Page<Complaint> pageData = complaintService.findAllByMemberIdAndStatusAndDeletedAtIsNullOrderByCreatedAtDesc(claims.getId(), status, page, size);
        logger.info("pageData=" + pageData);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 根据memberID查找会员名下某一投诉
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Result findComplaintByIdAndMemberId(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Complaint complaintInDb = complaintService.findByIdAndMemberId(id, claims.getId());
        logger.info("complaintInDb=" + complaintInDb);
        if (complaintInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        return new Result(StatusCode.SUCCESS_QUERY, complaintInDb);
    }
}
